package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.xmy.cultivate.entity.SkillMeans;
import com.xmy.cultivate.entity.SkillShutnum;

import com.xmy.cultivate.entity.SkillSports;
import com.xmy.cultivate.service.ISkillItemsSetService;
import com.xmy.cultivate.service.ISkillMeansService;
import com.xmy.cultivate.service.ISkillShutnumService;
import com.xmy.cultivate.service.ISkillSportsService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 关数设置 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-08-06
 */
@RestController
@RequestMapping("/api/skillShutnum")
public class SkillShutnumController extends BaseController{

    @Autowired
    ISkillItemsSetService iSkillItemsSetService;
    @Autowired
    ISkillShutnumService iSkillShutnumService;
    @Autowired
    ISkillMeansService iSkillMeansService;

    @Autowired
    ISkillSportsService iSkillSportsService;



    @GetMapping("/findAll")
    public Result findAll(@RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                          @RequestParam(value = "itemsId", required = false) String itemsId,  //培训项目设置id
                          @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id
                          @RequestParam(value = "status", required = false) String status,
                          @RequestParam(value = "subjectsId", required = false) String subjectsId
    ){
        IPage<SkillShutnum> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper<SkillShutnum> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("items_id",itemsId);
        queryWrapper.eq(StringUtils.isNotBlank(stationsId),"stations_id",stationsId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id",subjectsId);
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByAsc("num");
        iSkillShutnumService.page(iPage, queryWrapper);
        for (SkillShutnum skillShutnum : iPage.getRecords()){
            QueryWrapper<SkillMeans> skillMeansQueryWrapper = new QueryWrapper<>();
            skillMeansQueryWrapper.eq("shutnum_id",skillShutnum.getId());
//            skillMeansQueryWrapper.eq("item_id",itemsId);
//            skillMeansQueryWrapper.eq("shutnum_num",skillShutnum.getNum());
            long count = iSkillMeansService.count(skillMeansQueryWrapper);
            Integer isContent = 0;
            if (count > 0){
                isContent = 1;
            }
            skillShutnum.setIsContent(isContent);
        }

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    @PostMapping("/addSkillShutnum")
    public Result addSkillShutnum(@RequestBody SkillShutnum skillShutnum){
        QueryWrapper<SkillShutnum> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("num",skillShutnum.getNum());
        if (skillShutnum.getSubjectsId() !=  null) {
            queryWrapper.eq("subjects_id", skillShutnum.getSubjectsId());
        }
        if (skillShutnum.getYearClassId() !=  null) {
            queryWrapper.eq("year_class_id", skillShutnum.getYearClassId());
        }
        queryWrapper.eq(skillShutnum.getStationsId() !=null,"stations_id", skillShutnum.getStationsId());
        queryWrapper.eq("items_id", skillShutnum.getItemsId());
        long count = iSkillShutnumService.count(queryWrapper);
        if (count > 0){
            return new Result(Code.ERROR, null, "该关数已存在,无法添加");
        }
        skillShutnum.setCreatedId(this.adminId);
        boolean save = iSkillShutnumService.save(skillShutnum);
        if (!save){
            return new Result(Code.ERROR, null, "添加失败");
        }
        return new Result(Code.OK, null, "添加成功");

    }

    @PutMapping("/editSkillShutnum")
    public Result editSkillShutnum(@RequestBody SkillShutnum skillShutnum){
        SkillShutnum skillShutnumOld = iSkillShutnumService.getById(skillShutnum.getId());
        if (Objects.isNull(skillShutnumOld)){
            return new Result(Code.EXP_ERROR, null, "该数据不存在");
        }
        QueryWrapper<SkillShutnum> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("id",skillShutnum.getId());
        queryWrapper.eq("num",skillShutnum.getNum());
        if (skillShutnum.getSubjectsId() != null) {
            queryWrapper.eq("subjects_id", skillShutnum.getSubjectsId());
        }
        if (skillShutnum.getYearClassId() !=  null) {
            queryWrapper.eq("year_class_id", skillShutnum.getYearClassId());
        }
        queryWrapper.eq(skillShutnum.getStationsId() !=null,"stations_id", skillShutnum.getStationsId());
        queryWrapper.eq("items_id", skillShutnum.getItemsId());
        long count = iSkillShutnumService.count(queryWrapper);
        if (count > 0){
            return new Result(Code.ERROR, null, "该关数已存在,无法修改");
        }
        Integer oldShutnumNum = skillShutnumOld.getNum();
        skillShutnumOld.setNum(skillShutnum.getNum());
        skillShutnumOld.setName(skillShutnum.getName());
        skillShutnumOld.setSubjectsId(skillShutnum.getSubjectsId());
        skillShutnumOld.setYearClassId(skillShutnum.getYearClassId());
        skillShutnumOld.setStationsId(skillShutnum.getStationsId());
        skillShutnumOld.setItemsId(skillShutnum.getItemsId());
//        skillShutnumOld.setStatus(skillShutnum.getStatus());
        boolean update = iSkillShutnumService.updateById(skillShutnumOld);
        if (update){
            UpdateWrapper<SkillMeans> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("shutnum_id",skillShutnum.getId());
//            updateWrapper.eq("item_id",skillShutnum.getItemsId());
//            updateWrapper.eq("shutnum_num",oldShutnumNum);
            updateWrapper.set("shutnum_num",skillShutnum.getNum());
            iSkillMeansService.update(updateWrapper);
        }else {
            return new Result(Code.ERROR, null, "修改失败");
        }
        return new Result(Code.OK, null, "修改成功");
    }

    @DeleteMapping("/deleteSkillShutnum")
    public Result deleteSkillShutnum(@RequestBody Map reMap){
        List<String> ids = (List<String>) reMap.get("ids");
        if (ids == null || ids.isEmpty()){
            return new Result(Code.DELETE_ERROR, "", "请选择要删除的id");
        }
        QueryWrapper<SkillMeans> skillMeansQueryWrapper = new QueryWrapper<>();
        skillMeansQueryWrapper.in("shutnum_id",ids);
        long count = iSkillMeansService.count(skillMeansQueryWrapper);
        if (count > 0){
            return new Result(Code.ERROR, null, "关数中有未删除的内容，无法操作删除");
        }

        QueryWrapper<SkillSports> qw = new QueryWrapper<>();
        qw.in("shutnum_id",ids);
        long countQw = iSkillSportsService.count(qw);
        if (countQw > 0){
            return new Result(Code.ERROR, null, "关数中有上传的视频，无法操作删除");
        }

        QueryWrapper<SkillShutnum> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        boolean remove = iSkillShutnumService.remove(queryWrapper);
        if (remove) {
            return new Result(Code.OK, null, Code.DELETE_OK_MSG);
        }
        return new Result(Code.ERROR, null, Code.DELETE_ERROR_MSG);
    }


//    @DeleteMapping("/deleteSkillShutnum")
//    public Result deleteSkillShutnum(@RequestBody Map reMap){
//        List<String> ids = (List<String>) reMap.get("ids");
//        String itemsId = (String) reMap.get("itemsId");
//
//        if (ids == null || ids.isEmpty()) {
//            return new Result(Code.DELETE_ERROR, "", "请选择要删除的 id");
//        }
//
//        List<SkillShutnum> shutnumList = iSkillShutnumService.listByIds(ids);
//        if (shutnumList.isEmpty()) {
//            return new Result(Code.DELETE_ERROR, "", "未找到对应记录");
//        }
//
//        Set<Integer> nums = shutnumList.stream()
//                .map(SkillShutnum::getNum)
//                .collect(Collectors.toSet());
//
//        List<Integer> hasMeansNums = shutnumList.stream()
//                .filter(s -> {
//                    QueryWrapper<SkillMeans> qw = new QueryWrapper<>();
//                    qw.eq("shutnum_id", s.getId());
//                    return iSkillMeansService.count(qw) > 0;
//                })
//                .map(SkillShutnum::getNum)
//                .collect(Collectors.toList());
//
//        // 检查 SkillSports 表中是否存在关联记录
//        List<Integer> hasSportsNums = shutnumList.stream()
//                .filter(s -> {
//                    QueryWrapper<SkillSports> qw = new QueryWrapper<>();
//                    qw.eq("shutnum_id", s.getId());
//                    return iSkillSportsService.count(qw) > 0;
//                })
//                .map(SkillShutnum::getNum)
//                .collect(Collectors.toList());
//
//        List<String> canDeleteIds = new ArrayList<>();
//        List<Integer> cannotDeleteNums = new ArrayList<>();
//        List<Integer> cannotDeleteSportsNums = new ArrayList<>();
//
//        for (SkillShutnum s : shutnumList) {
//            if (hasMeansNums.contains(s.getNum())) {
//                cannotDeleteNums.add(s.getNum());
//            } else if (hasSportsNums.contains(s.getNum())) {
//                cannotDeleteSportsNums.add(s.getNum());
//            } else {
//                canDeleteIds.add(String.valueOf(s.getId()));
//            }
//        }
//
//        if (!canDeleteIds.isEmpty()) {
//            iSkillShutnumService.removeByIds(canDeleteIds);
//        }
//        // 构建错误信息
//        StringBuilder errorMsg = new StringBuilder();
//        boolean hasError = false;
//
//        if (!cannotDeleteNums.isEmpty()) {
//            errorMsg.append(cannotDeleteNums.stream()
//                    .sorted()
//                    .map(n -> "第" + n + "关")
//                    .collect(Collectors.joining("、"))
//                    + "有未删除的内容，无法删除");
//            hasError = true;
//        }
//
//        if (!cannotDeleteSportsNums.isEmpty()) {
//            if (hasError) errorMsg.append("；");
//            errorMsg.append(cannotDeleteSportsNums.stream()
//                    .sorted()
//                    .map(n -> "第" + n + "关")
//                    .collect(Collectors.joining("、"))
//                    + "有上传的视频，无法删除");
//            hasError = true;
//        }
//
//        if (hasError) {
//            if (!canDeleteIds.isEmpty()) {
//                errorMsg.append("；已删除" + canDeleteIds.size() + "条记录");
//            }
//            return new Result(Code.DELETE_ERROR, "", errorMsg.toString());
//        }
//
//        return new Result(Code.OK, "", "删除成功");
//    }








}
